﻿using System.Text;

namespace Lib.Common;

/// <summary>
/// 随机数生成器
/// </summary>
public static class RNG {
    /// <summary>
    /// 按当前日期和时间生成随机数
    /// </summary>
    /// <param name="Len">附加随机数长度</param>
    public static string DateTime(int Len = 4) {
        return System.DateTime.Now.ToString("yyyyMMddHHmmss") + Number(Len);
    }
    /// <summary>
    /// 生成0-9随机数(默认4位)
    /// </summary>
    /// <param name="Len">生成长度</param>
    public static string Number(int Len = 4) {
        var sb = new StringBuilder(Len);
        for (int i = 0; i < Len; i++) {
            sb.Append(Random.Shared.Next(9));
        }
        return sb.ToString();
    }
    /// <summary>
    /// 生成0-9随机数(默认4位)
    /// </summary>
    /// <param name="Len">生成长度</param>
    public static int Digit(int Len = 4) {
        return int.Parse(Number(Len));
    }
    /// <summary>
    /// 获得随机字符串 
    /// </summary>
    /// <param name="Len">随机字符串 长度</param>
    /// <returns></returns>
    public static string Key(int Len = 6) {
        return Get(Len);
    }
    /// <summary>
    /// 获得随机字符串，可指定字符源
    /// </summary>
    /// <param name="Len">获得字符长度，默认6位</param>
    /// <param name="Source">字符源</param>
    public static string Get(int Len = 6, string Source = null) {
        Source ??= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        var sb = new StringBuilder();
        int Length = Source.Length;
        for (int i = 0; i <= Len - 1; i++) {
            sb.Append(Source[Random.Shared.Next(Length)]);
        }
        return sb.ToString();
    }
}

